ReactJS Ultra For Beginners

🔄 React Query (TanStack Query)


What is React Query?

  • A powerful data synchronization library for React
  • Handles server state management (caching, background updates, error handling)
  • Provides hooks for fetching, caching, and updating data
  • Reduces boilerplate for data fetching

📝 Basic Setup

import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query"; // Create a client const queryClient = new QueryClient(); // Wrap your app function App() { return ( <QueryClientProvider client={queryClient}> <UserList /> </QueryClientProvider> ); } // Use in component function UserList() { const { data: users, isLoading, error, } = useQuery({ queryKey: ["users"], queryFn: () => fetch("/api/users").then((res) => res.json()), }); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; return ( <ul> {users?.map((user) => ( <li key={user.id}>{user.name}</li> ))} </ul> ); }

🔑 Core Hooks

1. useQuery - For fetching data:

function UserProfile({ userId }) { const { data: user, isLoading, error, refetch, } = useQuery({ queryKey: ["user", userId], queryFn: () => fetchUser(userId), enabled: !!userId, // Only run if userId exists staleTime: 5 * 60 * 1000, // 5 minutes cacheTime: 10 * 60 * 1000, // 10 minutes }); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error.message}</div>; return ( <div> <h1>{user.name}</h1> <p>{user.email}</p> <button onClick={() => refetch()}>Refresh</button> </div> ); }

2. useMutation - For updating data:

function CreateUser() { const mutation = useMutation({ mutationFn: (newUser) => createUser(newUser), onSuccess: (data) => { // Invalidate and refetch users queryClient.invalidateQueries({ queryKey: ["users"] }); }, onError: (error) => { console.error("Error creating user:", error); }, }); const handleSubmit = (userData) => { mutation.mutate(userData); }; return ( <form onSubmit={handleSubmit}> <button type="submit" disabled={mutation.isPending}> {mutation.isPending ? "Creating..." : "Create User"} </button> </form> ); }

🎯 Common Patterns

Data Fetching with Parameters:

function PostList({ category }) { const { data: posts, isLoading } = useQuery({ queryKey: ["posts", category], queryFn: () => fetchPosts(category), enabled: !!category, }); if (isLoading) return <div>Loading posts...</div>; return ( <div> {posts?.map((post) => ( <Post key={post.id} post={post} /> ))} </div> ); }

Optimistic Updates:

function TodoList() { const queryClient = useQueryClient(); const updateTodoMutation = useMutation({ mutationFn: updateTodo, onMutate: async (newTodo) => { // Cancel outgoing refetches await queryClient.cancelQueries({ queryKey: ["todos"] }); // Snapshot previous value const previousTodos = queryClient.getQueryData(["todos"]); // Optimistically update queryClient.setQueryData(["todos"], (old) => old.map((todo) => todo.id === newTodo.id ? { ...todo, ...newTodo } : todo ) ); return { previousTodos }; }, onError: (err, newTodo, context) => { // Rollback on error queryClient.setQueryData(["todos"], context.previousTodos); }, onSettled: () => { // Always refetch after error or success queryClient.invalidateQueries({ queryKey: ["todos"] }); }, }); return ( <div> {todos?.map((todo) => ( <TodoItem key={todo.id} todo={todo} onUpdate={(updates) => updateTodoMutation.mutate(updates)} /> ))} </div> ); }

Infinite Queries:

function InfinitePostList() { const { data, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading } = useInfiniteQuery({ queryKey: ["posts"], queryFn: ({ pageParam = 1 }) => fetchPosts(pageParam), getNextPageParam: (lastPage, pages) => { return lastPage.hasMore ? pages.length + 1 : undefined; }, }); if (isLoading) return <div>Loading...</div>; return ( <div> {data.pages.map((page, i) => ( <div key={i}> {page.posts.map((post) => ( <Post key={post.id} post={post} /> ))} </div> ))} <button onClick={() => fetchNextPage()} disabled={!hasNextPage || isFetchingNextPage} > {isFetchingNextPage ? "Loading more..." : hasNextPage ? "Load More" : "Nothing more to load"} </button> </div> ); }

🔧 Advanced Features

Query Invalidation:

const queryClient = useQueryClient(); // Invalidate specific queries queryClient.invalidateQueries({ queryKey: ["users"] }); // Invalidate queries with pattern queryClient.invalidateQueries({ queryKey: ["users"], exact: false }); // Invalidate all queries queryClient.invalidateQueries();

Prefetching:

function UserList() { const queryClient = useQueryClient(); const prefetchUser = (userId) => { queryClient.prefetchQuery({ queryKey: ["user", userId], queryFn: () => fetchUser(userId), }); }; return ( <div> {users?.map((user) => ( <div key={user.id} onMouseEnter={() => prefetchUser(user.id)}> {user.name} </div> ))} </div> ); }

Background Refetching:

function RealTimeData() { const { data, isLoading } = useQuery({ queryKey: ["real-time-data"], queryFn: fetchRealTimeData, refetchInterval: 5000, // Refetch every 5 seconds refetchIntervalInBackground: true, // Continue refetching when tab is not active }); return <div>{/* Your component */}</div>; }

🎯 Error Handling

function UserProfile({ userId }) { const { data: user, error, isError, } = useQuery({ queryKey: ["user", userId], queryFn: () => fetchUser(userId), retry: 3, // Retry 3 times on failure retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000), }); if (isError) { return ( <div> <h2>Error loading user</h2> <p>{error.message}</p> <button onClick={() => refetch()}>Try again</button> </div> ); } return <div>{/* User profile */}</div>; }

🔄 Mutations with Optimistic Updates

function TodoItem({ todo }) { const queryClient = useQueryClient(); const toggleMutation = useMutation({ mutationFn: (todoId) => toggleTodo(todoId), onMutate: async (todoId) => { await queryClient.cancelQueries({ queryKey: ["todos"] }); const previousTodos = queryClient.getQueryData(["todos"]); queryClient.setQueryData(["todos"], (old) => old.map((todo) => todo.id === todoId ? { ...todo, completed: !todo.completed } : todo ) ); return { previousTodos }; }, onError: (err, todoId, context) => { queryClient.setQueryData(["todos"], context.previousTodos); }, onSettled: () => { queryClient.invalidateQueries({ queryKey: ["todos"] }); }, }); return ( <div> <input type="checkbox" checked={todo.completed} onChange={() => toggleMutation.mutate(todo.id)} /> <span>{todo.text}</span> </div> ); }

⚠️ Best Practices

  1. Use descriptive query keys - make them unique and meaningful
  2. Handle loading and error states - always provide user feedback
  3. Use staleTime and cacheTime - optimize for your use case
  4. Invalidate queries after mutations - keep data in sync
  5. Use optimistic updates - improve perceived performance
  6. Prefetch data - improve user experience
  7. Handle errors gracefully - provide retry mechanisms